import json
import os

import numpy as np
import mat4py
import scipy.io as scio

from array import array
from loguru import logger
import matlab.engine
from PIL import Image

#import pai_img

#from models.data_model import Acquisition

class PAIAnalysis(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        super().__init__()

        ## 初始化matlab封装的图像分析模块
        #self.paiimg = pai_img.initialize()
        
        eng = matlab.engine.start_matlab()

        mat = eng.magic(3)
        print(type(mat))
        print(len(mat._data))

        python_list = [1, 4, 9]
        a = matlab.double(python_list)
        print(len(a._data))
        print(a._data.tolist())
        #a.toarray()
        # a = matlab.double([1, 4, 9])
        # a = matlab.double([a, 16])
        b = eng.sqrt(a)
        print(b)

        matlab_spectrum_path = os.getcwd() + "/matlab_scripts/image_signal_analysis"
        eng.cd(matlab_spectrum_path)
        #result = eng.DataExtractFromBin("D:/Project/Data/YCS-牛长骨-1-P4-2V-2023-03-28-23-54-06/2023-03-30-00-26-05/Rawdata_FPGA1_Frame5.bin")
        bin_file_path = "D:/Project/Data/YCS-牛长骨-1-P4-2V-2023-03-28-23-54-06/2023-03-30-00-26-05/Rawdata_FPGA1_Frame5.bin"
        acq_parameter_file_path = "D:"
        matlab_channels = matlab.double([1, 16, 32])
        modality_mode = 1
        valid_flag = 1
        matlab_range = matlab.double([100, 110])
        result = eng.PAUSSignalExtract(bin_file_path, 
                              acq_parameter_file_path,
                              float(modality_mode), 
                              matlab_channels, 
                              float(valid_flag), 
                              matlab_range)
        

        print(type(result["selectedchannels"]))

        #print(result)
        # print(result["signals"].size)
        # # memoryview = result["signals"].tomemoryview()
        # signal = np.array(result["signals"])
        # signal = signal.transpose()
        # print(signal)

        self.current_acquisition_id = 0
        self.current_acquisition_path = None
        self.current_acquisition_file = None
        logger.debug("create an instance of PAIAnalysis successfully.")
    
    def setCurrentAcquisitionID(self, acquisition_id):
        self.current_acquisition_id = acquisition_id
    
    # def getCurrentAcquisitionPath(self):
    #     existing_acq = Acquisition.query.filter(Acquisition.id == self.current_acquisition_id).one_or_none()
    #     if existing_acq is None:
    #             return
        
    #     self.current_acquisition_path = existing_acq.acq_data_path
    #     return self.current_acquisition_path
    
    def setCurrentAcquisitionFile(self, bin_file):
        self.current_acquisition_file = bin_file


# When passing a list as a parameter from Python to a MATLAB function, 
# the MATLAB function treats the list as a MATLAB cell array. 
# Each element of the list becomes a cell in the cell array.


if __name__ == '__main__':
#################################################################
# define a global single variable
    matlab_eng = matlab.engine.start_matlab()
    matlab_scripts_path = os.getcwd() + "/matlab_scripts/image_signal_analysis"
    matlab_eng.cd(matlab_scripts_path)

    #pai_analysis = PAIAnalysis()
    pa_image_list = []
    example_img_path = os.getcwd() + "/matlab_scripts/const_file"

    img = Image.open(example_img_path + "/BOS_result.bmp")
    pixel_matrix = np.array(img, 'uint8')
    dimension = pixel_matrix.shape
    image_width = dimension[1]
    image_height = dimension[0]
    # 将numpy数组转换为一维数组
    array_1d = pixel_matrix.flatten("F")
    # 将获取数据转换为bytes
    pixel_bytes = array_1d.tobytes()
    

    pa_image_list.append(matlab.uint8(pixel_bytes))
    pa_image_list.append(matlab.uint8(pixel_bytes))

    wavelengths = matlab.double([690, 700, 710, 720])

    logger.debug("input arguments of matlab function: PAMolecularImagingUnmixing. count of PA images:{0}, image width:{1}, image height:{2}, input laser wavelength list:{3}", len(pa_image_list), image_width, image_height, wavelengths)

    [mineral_result, lipid_result, collagen_result, Hb_result, HHb_result, BOS_result] = matlab_eng.PAMolecularImagingUnmixing(pa_image_list, matlab.uint8(pixel_bytes), float(image_width), float(image_height), wavelengths, nargout = 6)